//
//  UIViewController+Swizzling.m
//  xk100
//
//  Created by xiaokang on 2017/5/2.
//  Copyright © 2017年 xiaokang. All rights reserved.
//

#import "UIViewController+Swizzling.h"
#import <objc/runtime.h>

@implementation UIViewController (Swizzling)


+ (void)load {
    // 通过class_getInstanceMethod()函数从当前对象中的method list获取method结构体，如果是类方法就使用class_getClassMethod()函数获取。
    Method viewWillAppear = class_getInstanceMethod([self class], @selector(viewWillAppear:));
    Method swiz_viewWillAppear = class_getInstanceMethod([self class], @selector(swiz_viewWillAppear:));
    Method viewWillDisappear = class_getInstanceMethod([self class], @selector(viewWillDisappear:));
    Method swiz_viewWillDisappear = class_getInstanceMethod([self class], @selector(swiz_viewWillDisappear:));
    /**
     *  我们在这里使用class_addMethod()函数对Method Swizzling做了一层验证，如果self没有实现被交换的方法，会导致失败。
     *  而且self没有交换的方法实现，但是父类有这个方法，这样就会调用父类的方法，结果就不是我们想要的结果了。
     *  所以我们在这里通过class_addMethod()的验证，如果self实现了这个方法，class_addMethod()函数将会返回NO，我们就可以对其进行交换了。
     */
    if (!class_addMethod([self class], @selector(swiz_viewWillAppear:), method_getImplementation(swiz_viewWillAppear), method_getTypeEncoding(swiz_viewWillAppear))) {
        method_exchangeImplementations(viewWillAppear, swiz_viewWillAppear);
    }
    
    if (!class_addMethod([self class], @selector(swiz_viewWillDisappear:), method_getImplementation(swiz_viewWillDisappear), method_getTypeEncoding(swiz_viewWillDisappear))) {
        method_exchangeImplementations(viewWillDisappear, swiz_viewWillDisappear);
    }
}

// 我们自己实现的方法，也就是和self的ViewWillAppear方法进行交换的方法。
- (void)swiz_viewWillAppear:(BOOL)animated {
    
    NSString *str = [NSString stringWithFormat:@"%@", self.class];
    if(![str containsString:@"UI"] && ![str containsString:@"Navigation"] && ![str containsString:@"TabBar"]){
//        NSLog(@"统计打点开始 : %@", self.class);
        [MobClick beginLogPageView:str];// 友盟页面统计:开始
    }
    [self swiz_viewWillAppear:animated];
}

- (void)swiz_viewWillDisappear:(BOOL)animated {
    
    NSString *str = [NSString stringWithFormat:@"%@", self.class];
    if(![str containsString:@"UI"] && ![str containsString:@"Navigation"] && ![str containsString:@"TabBar"]){
//        NSLog(@"统计打点结束 : %@", self.class);
        [SVProgressHUD dismiss];// 所有页面退出时取消SVProgressHUD的状态
        [MobClick endLogPageView:str];// 友盟页面统计:结束
    }
    [self swiz_viewWillDisappear:animated];
}

@end

